package com.pf.java.ThreadTest;

/**
 * 线程安全问题
 *
 * ClassName:Thread04
 * Package:com.pf.java.ThreadTest
 *
 * @author: pf
 * @date: 2021/11/22-9:54
 */
public class Thread04 {

    public static void main(String[] args) {
        Ticket ticket = new Ticket(100);
        SellTask task = new SellTask(ticket);
        new Thread(task, "John").start();
        new Thread(task, "Mary").start();
        new Thread(task, "Tony").start();


    }

    private static class Ticket {

        private int amount;

        public Ticket(int amount) {
            this.amount = amount;
        }

        public int getAmount() {
            return amount;
        }

        public void buy(int amount) {
            if(this.amount < amount) {
                throw  new IllegalArgumentException("余量不足！");
            }

            // 校验花费一些时间
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 通过校验成功购票
            this.amount -= amount;
            String name = Thread.currentThread().getName();
            System.out.println(name + "购买成功,剩余" + this.amount);

        }

    }


    private static class SellTask implements Runnable {

        private Ticket ticket;

        public SellTask(Ticket ticket) {
            this.ticket = ticket;
        }

        @Override
        public void run() {
            ticket.buy(1);
        }
    }

}
